<template>
	<web-view class="y-flex-1" ref="webview" src="/hybrid/html/video/my-list-player.html" @onPostMessage="handleMessage"></web-view>
</template>

<script>
	import { setVolume, getVolume, saveBase64ImageToAlbum } from '@/assets/js/native.js'
	export default {
		props: {
			src: {
				type: String,
				default: ''
			},
			poster: {
				type: String,
				default: ''
			},
			title: {
				type: String,
				default: ''
			},
			type: {
				type: String,
				default: 'auto'
			},
			isLive: {
				type: Boolean,
				default: false
			},
			autoplay: {
				type: Boolean,
				default: false
			}
		},
		methods: {
			handleMessage (e) {
				e.detail.data.forEach(item => {
					if ( item.ready ) {
						uni.getScreenBrightness({
							success: res => {
								const arg = {
									src: this.src,
									title: this.title || '',
									poster: this.poster || undefined,
									autoplay: this.autoplay,
									type: this.type,
									isLive: this.isLive,
									initialVolume: getVolume(),
									initialLight: res.value
								}
								this.$refs.webview && this.$refs.webview.evalJS(`setVideo('${encodeURIComponent(JSON.stringify(arg))}');`)
							}
						})
					}
					if ( item.download ) {
						this.$emit('download', {
							url: this.src,
							title: this.title
						})
					}
					if ( item.seeklight >= 0 ) {
						uni.setScreenBrightness({
							value: item.seeklight
						})
					}
					if ( item.seekvolume >= 0 ) {
						setVolume(item.seekvolume)
					}
					if ( item.capturesaved ) {
						if ( item.capturesaved.code != 200 ) {
							saveBase64ImageToAlbum(item.capturesaved.data.base64, item.capturesaved.fileName).then(path => {
								this.showToast('保存到相册成功')
							}).catch(() => {
								this.showToast('保存到相册失败')
							})
						}
					}
					if ( item.directionchange ) {
						if ( item.directionchange.code != 200 ) {//锁定屏幕方向失败
							var direction = item.directionchange.to//预期屏幕方向
							if ( direction ) plus.screen.lockOrientation(direction)//锁定屏幕方向
							else plus.screen.unlockOrientation()//解除屏幕方向锁定
						}
					}
					if ( item.destroyed ) {
						this.$emit('destroyed')
					}
				})
			},
			play () {
				this.$refs.webview && this.$refs.webview.evalJS(`play();`)
			},
			pause () {
				this.$refs.webview && this.$refs.webview.evalJS(`pause();`)
			},
			showToast (data) {
				this.$refs.webview && this.$refs.webview.evalJS(`showToast('${encodeURIComponent(JSON.stringify(data))}');`)
			}
		}
	}
</script>

<style>
</style>